package com.yfuxdeer.youchat.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.yfuxdeer.youchat.R;
import com.yfuxdeer.youchat.pojo.Moment;
import com.yfuxdeer.youchat.service.FriendService;
import com.yfuxdeer.youchat.service.MomentService;
import com.yfuxdeer.youchat.utils.Store;


public class PublishMomentActivity extends AppCompatActivity {

    private Button cancel;
    private Button publish;
    private EditText content;
    private Store store = Store.getInstance();
    private Moment moment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_moment);
        //注册广播
        registerReceiver(publishMomentReceiver, new IntentFilter("com.yfuxdeer.youchat.publishMomentReceiver"));

        cancel = findViewById(R.id.cancel);
        publish = findViewById(R.id.publish);
        content = findViewById(R.id.content);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                moment = new Moment();
                moment.setHost_id(store.getCurrentUser().getUsername());
                moment.setContent(content.getText().toString());

                //调用服务写数据库
                Intent intent = new Intent(getApplicationContext(), MomentService.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("moment", moment);
                bundle.putSerializable("method", MomentService.METHOD.PUBLISH);
                intent.putExtras(bundle);
                startService(intent);
            }
        });
    }

    private BroadcastReceiver publishMomentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            MomentService.RESULT result = (MomentService.RESULT) bundle.getSerializable("result");
            switch (result) {
                case SUCCESS:
                    Toast.makeText(getApplicationContext(), "发表成功", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case NETWORK_EXCEPTION:
                    Toast.makeText(getApplicationContext(), "网络异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
}